package com.example.project.controller;

import com.example.project.common.AjaxResult;
import com.example.project.model.Demo;
import com.example.project.service.IDemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 演示专用 前端控制器
 * </p>
 *
 * @author ss
 * @since 2021-12-02
 */
@RestController
@RequestMapping("/demo")
public class DemoController {

    @Autowired
    private IDemoService demoService;

    /**
     * 获取demo列表
     */
    @GetMapping("/list")
    public AjaxResult list() {
        List<Demo> demos = demoService.list();
        return AjaxResult.success(demos);
    }

    /**
     * 根据id获取demo信息
     */
    @GetMapping("/getById")
    public AjaxResult getById(Integer id) {
        Demo demo = demoService.getById(id);
        return AjaxResult.success(demo);
    }

    /**
     * 新增demo
     */
    @PostMapping("/add")
    public AjaxResult add(@Validated Demo demo) {
        demo.setCreated(LocalDateTime.now());
        return demoService.save(demo) ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 修改demo
     */
    @PostMapping("/edit")
    public AjaxResult edit(@Validated Demo demo) {
        return demoService.updateById(demo) ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 删除demo
     */
    @DeleteMapping("/delete")
    public AjaxResult delete(Integer id) {
        return demoService.removeById(id) ? AjaxResult.success() : AjaxResult.error();
    }

}
